package cn.itsource.ymcc.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign的拦截器
 *
 *  将当前请求的请求头中的token
 *  携带给Feign的请求头
 */
@Component
public class TokenForwordFeignInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        //1.拿到当前请求
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //2.得到请求头中的token
        String token = request.getHeader("Authorization");
        if(StringUtils.hasLength(token)){
            //3.设置给下一个请求头
            requestTemplate.header("Authorization",token);
        }
    }
}